package app

import (
	"context"
	"fmt"
	imapp "go.manyji.com/im3/app"
	"go.manyji.com/lib/config"
	"go.manyji.com/lib/encoding/json"
	logger "go.manyji.com/lib/log"
	"net/http"
	"net/url"
	"sieve_admin_server/app/server"
	"strconv"
)

var (
	fCookieName = config.String("session.cookie", "session", "session cookie name")
	fPathRoot   = config.String("web.pathroot", "/", "path root")
)

// 处理工号登录逻辑
func handlerJobNumberLogin(w http.ResponseWriter, r *http.Request) {

	var (
		uid, _ = strconv.Atoi(r.URL.Query().Get("uid"))
		//uid = 240
		f = func() {
			userSrv := AppInjector.Router.UserAPI.UserSrv
			logger.Info(fmt.Sprintf("%+v", userSrv.CreateOrUpdateStaffUser(context.Background(), uint64(uid), server.CheckRoleType(uid))))
		}
	)

	server.HandleLogin(w, r, f)

	return
}

func Login(w http.ResponseWriter, r *http.Request) {

	loginMethod := server.CheckLoginMethod(r)
	if loginMethod == 1 {
		handlerJobNumberLogin(w, r)
		return
	}

	w.Header().Set("Access-Control-Allow-Origin", "*")

	userAuth := AppInjector.Router.UserAuthAPI

	if err := r.ParseForm(); err != nil {
		w.WriteHeader(http.StatusBadRequest)
		_, _ = w.Write([]byte(err.Error()))
		return
	}
	args := r.PostForm
	c := &server.Context{
		Args: url.Values{},
		Http: &server.ContextHttp{
			ResponseWriter: w,
			Request:        r,
		},
	}

	ret := userAuth.Login(context.Background(), c, map[string]interface{}{
		"username": args.Get("u"),
		"password": args.Get("p"),
	})

	bt, _ := json.Marshal(ret)
	_, _ = w.Write(bt)
}

func Logout(w http.ResponseWriter, r *http.Request) {

	w.Header().Set("Access-Control-Allow-Origin", "*")

	userAuth := AppInjector.Router.UserAuthAPI

	gotUid, userType := server.GetLoginType(r)

	if userType == 2 {
		c := &server.Context{
			Args: url.Values{},
			Http: &server.ContextHttp{
				ResponseWriter: w,
				Request:        r,
			},
		}

		userAuth.Logout(context.Background(), c, uint64(gotUid))
		http.SetCookie(w, &http.Cookie{
			Name:   "app" + strconv.Itoa(imapp.AppId()) + "_" + *fCookieName,
			MaxAge: -1,
			Path:   *fPathRoot,
		})

		http.Redirect(w, r, *fPathRoot, http.StatusFound)
		server.HandleIndex(w, r)
		return
	}

	server.HandleLogout(w, r)

	return
}

//
//func Logout(w http.ResponseWriter, r *http.Request) {
//
//	w.Header().Set("Access-Control-Allow-Origin", "*")
//
//	userAuth := AppInjector.Router.UserAuthAPI
//
//	gotUid, userType := server.GetLoginType(r)
//
//	if userType == 2 {
//		c := &server.Context{
//			Args: url.Values{},
//			Http: &server.ContextHttp{
//				ResponseWriter: w,
//				Request:        r,
//			},
//		}
//
//		userAuth.Logout(context.Background(), c, uint64(gotUid))
//		http.SetCookie(w, &http.Cookie{
//			Name:   "app" + strconv.Itoa(imapp.AppId()) + "_" + *fCookieName,
//			MaxAge: -1,
//			Path:   *fPathRoot,
//		})
//
//		http.Redirect(w, r, *fPathRoot, http.StatusFound)
//		server.HandleIndex(w, r)
//		return
//	}
//
//	server.HandleIndex(w, r)
//
//	return
//}
